package _2025_4_13;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class demo2 {
    private final static ReentrantLock locker1=new ReentrantLock();
    private final static ReentrantLock locker2=new ReentrantLock();

    public static void main(String[] args) {
        Thread t1 = new Thread (()->{
               if(locker1.tryLock()){
                   System.out.println("t1线程h获取到locker1");
                   try {
                       Thread.sleep(100);
                   } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                   }
                   if(locker2.tryLock()){//尝试获取locker2
                       System.out.println("t1线程获取到locker2");
                       locker2.unlock();//释放locker2
                   }else {
                       System.out.println("t1线程获locker2失败，放弃");
                   }
                   //释放locker1
                   locker1.unlock();
               }else{
                   System.out.println("t1线程获取lokcer1失败，放弃");
               }
        });
        Thread t2 = new Thread (()->{
            if(locker2.tryLock()){
                System.out.println("t2线程h获取到locker2");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                if(locker1.tryLock()){//尝试获取locker1
                    System.out.println("t2线程获取到locker1");
                    locker1.unlock();//释放locker1
                }else {
                    System.out.println("t2线程获locker1失败，放弃");
                }
                //释放locker2
                locker2.unlock();
            }else{
                System.out.println("t2线程获取lokcer2失败，放弃");
            }
        });
        t1.start();
        t2.start();
    }
}
